package helper.base.theListenerHelperTest

import org.junit.Test

internal class ListenerHelperTest2 {
    data class ZoneConstraint(
        val name: String,
        val constraint: String,
    )

    interface ElementListener<T> {
        fun onElementAdded(element: T)
    }

    class ListenedArrayList<E> : ArrayList<E>() {
        private val listeners: ArrayList<ElementListener<E>> = ArrayList()

        fun addElementListener(listener: ElementListener<E>) {
            listeners.add(listener)
        }

        override fun add(element: E): Boolean {
            val added = super.add(element)
            if (added) {
                listeners.forEach {
                    it.onElementAdded(element)
                }
            }
            return added
        }
    }


    @Test
    fun t1() {
        val zoneConstraints = ListenedArrayList<ZoneConstraint>()
        val linkedHashMap = LinkedHashMap<String, ZoneConstraint>()

        zoneConstraints.addElementListener(
            object : ElementListener<ZoneConstraint> {
                override fun onElementAdded(
                    element: ZoneConstraint
                ) {
                    linkedHashMap[element.name] = element
                }
            }
        )

        fun pln() {
            println("-----pln-----")
            println(zoneConstraints)
            println(linkedHashMap)
        }

        pln()
        zoneConstraints.add(
            ZoneConstraint(
                "n1",
                "c1",
            )
        )
        pln()
    }
}